//
//  AppDelegate.m
//  Trading365
//
//  Created by yifei tong on 11-12-14.
//  Copyright (c) 2011年 dhc. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginView.h"
#import "Session.h"
#import "XmlRpc.h"
#import "Type.h"
#import "DHCUtil.h"

#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <unistd.h>
#import <SystemConfiguration/SCNetworkReachability.h>
#import <netinet/in.h> 
#import "myToast.h"
#import "InfoType.h"
//#import <CoreLocation/CoreLocation.h>

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController=_viewController;
@synthesize loadingViewController = _loadingViewController;
@synthesize ver_server;
@synthesize m_bConnect;

- (void)dealloc
{
    [_window release];
    [_viewController release];
    [ver_server release];
    [locmanager release];
    [super dealloc];
}

- (BOOL) connectedToNetwork
{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    //zeroAddress.sin_port = htons(8443); //端口   htons 把16位值从主机字节序转换成网络字节序
	//zeroAddress.sin_addr.s_addr = inet_addr("172.16.15.130"); //IP
    
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        NSLog(@"无法连接到网络");
        return NO;
    }
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable && !needsConnection) ? YES : NO;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{    
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleBlackOpaque];
    
    //先显示UITabBarController
    [self.window addSubview:_viewController.view];

   
    //探测网络是否已经连接
    m_bConnect = [self connectedToNetwork];
    if (m_bConnect == NO)
    {
        NSLog(@"无法连接到网络");
        
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"网络"
                                                       message:@"无法连接到网络"
                                                      delegate:self
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil];
        [alert show];
        [alert release];
        return NO;
    }
    else
    {
        NSLog(@"连接到网络成功");
        //在此之上，显示LoginView，随后，在loginview成功后，移除自己即可
        LoginView *login=[[LoginView alloc] init];
        [login setFlagLoginType:INFO_TYPE_LOGIN_MANU];
        [login.view setFrame:CGRectMake(0, 0, 320, 480)];
        if ([[Session share] isLogined] == NO)
        {
            login.view.hidden = YES;
            [self.window addSubview:login.view];
        }
        [self.window makeKeyAndVisible];
        [login release];
    }


    
//    //在UITabBar又上角带红圈中数字
//    [[[[self.viewController tabBar] items] objectAtIndex:3] setBadgeValue:@"18"];
//    [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%d",number]];
    //tabBarItem获取方法：[[[tabBarCtr tabBar] items] objectAtIndex:i];【tabBarCtr为APPDelegate中的UITabBarController,i表示第i个TabBar】
    // number为显示在TabBar上的整数
    
//    [[[self.viewController.viewControllers objectAtIndex:0] tabBarItem] setBadgeValue:@"10"]; 
    [self loadLoadingView];
    [self SetTimer];
    
//    //在应用icon又上角带红圈中数字
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    
     
    return YES;
}


- (void)loadingViewAnimationDone
{
    self.loadingViewController = nil;
}
- (void)loadLoadingView
{
    self.loadingViewController
    = [[[DSLoadingViewController alloc] initWithNibName:@"DSLoadingViewController" bundle:nil] autorelease];
    [self.window addSubview:self.loadingViewController.view];
}

- (void)loadMainView
{    

    [self.window bringSubviewToFront:self.loadingViewController.view];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(loadingViewAnimationDone)];
    [UIView setAnimationDuration:3];
    
    self.loadingViewController.view.alpha = 0;
    
    [UIView commitAnimations];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}
-(void) setMainViewCtl:(NavigationMainViewController*) mainViewCtl
{
    _mainViewCtl = mainViewCtl;
}

-(NavigationMainViewController*) getMainViewCtl
{
    return  _mainViewCtl;
}

-(void) setMissionTodoViewCtl:(RootMissionToDo*) missionTodoViewCtl
{
    _missionTodoViewCtl = missionTodoViewCtl;
}
-(RootMissionToDo*) getMissionTodoViewCtl
{
    return _missionTodoViewCtl;
}
//
-(void) setMoreViewCtl:(RootMore*) moreViewCtl
{
    _moreViewCtl = moreViewCtl;
}
-(RootMore*) getMoreViewCtl
{
    return _moreViewCtl;
}


#pragma mark - my fun
//******************************************************
// Method:     SetTimer
// Access:     public 
// Returns:    void
// Parameter:  void
// Note:	   开启定时器
// Author      muzongcun  2012/05/10 create
//*******************************************************
- (void) SetTimer
{
    m_timer = [NSTimer scheduledTimerWithTimeInterval:TIME_INTERVAL target:self selector:@selector(OnTimer) userInfo:nil repeats:YES];
}

//******************************************************
// Method:     KillTimer
// Access:     public 
// Returns:    void
// Parameter:  void
// Note:	   关闭定时器
// Author      muzongcun  2012/05/10 create
//*******************************************************
- (void)KillTimer
{
    if (m_timer) 
    {
        [m_timer invalidate];
    }
}

//******************************************************
// Method:     OnTimer
// Access:     public 
// Returns:    void
// Parameter:  void
// Note:	   定时器工作
// Author      muzongcun  2012/05/10 create
//*******************************************************
- (void)OnTimer
{
    if ([[Session share] isLogined] == NO ) 
    {
        return;
    }
    locmanager                  = [[CLLocationManager alloc] init];
    locmanager.delegate         = self;  
    locmanager.desiredAccuracy  = kCLLocationAccuracyBest;
    [locmanager startUpdatingLocation];
    CLLocationDegrees latitude  = [[locmanager location] coordinate].latitude;
    CLLocationDegrees longitude = [[locmanager location] coordinate].longitude;

    NSString* strLatitude       = [NSString  stringWithFormat:@"%.15f",latitude];
    NSString* strLongitude      = [NSString  stringWithFormat:@"%.15f",longitude];
    NSString* strCurrentTime    = [self getCurrentTime];
    
    NSLog(@"placeMarkLocation=%.15f,%.15f",latitude,longitude);
    
    XmlRpc *xml = [[XmlRpc alloc] init];
    [xml updateCurrentPoint:strLatitude longitude:strLongitude currentTime:strCurrentTime]; 
//    NSMutableDictionary * dic = [xml updateCurrentPoint:strLatitude longitude:strLongitude currentTime:strCurrentTime]; 
//    NSLog(@"----OnTimer");
    [xml release];
    
}

//******************************************************
// Method:     getCurrentTime
// Access:     public 
// Returns:    void
// Parameter:  
// Note:	   得到当前时间
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (NSString *)getCurrentTime
{
    NSDate *        date     = [NSDate date];
    NSCalendar *calendar     = [NSCalendar currentCalendar];
    NSDateComponents * comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
    
    return [NSString stringWithFormat:@"%.4d-%.2d-%.2d %.2d:%.2d:%.2d",[comps year],[comps month],[comps day],[comps hour],[comps minute],[comps second]];
}

@end
